<script lang="ts">
import {
  defineComponent,
  reactive,
  toRefs,
  type PropType
} from 'vue'

type FormPosition = 'left' | 'right' | 'center'
type HexColor = `#${string}`

export default defineComponent({
  name: 'LoginTemplate',
  props: {
    formPosition: {
      type: String as PropType<FormPosition>,
      required: true, // 必须显式传值
      validator: (value: unknown) => {
        return typeof value === 'string' && ['left', 'right', 'center'].includes(value as FormPosition)
      }
    },
    backgroundColor: {
      type: String as PropType<HexColor>,
      default: '#ffffff',
      validator: (value: string) => {
        return /^#([A-Fa-f0-9]{3}){1,2}$/.test(value)
      }
    },
    backgroundImage: {
      type: [String, Object] as import('vue').PropType<string | { default: string }>,
      default: null,
      validator: (value: any) => {
        if (!value) return true // 允许空值
        if (typeof value === 'string') {
          // 验证字符串是否为有效URL或base64
          return /^(https?:\/\/|data:image|\.?\/)/.test(value)
        }
        // 验证是否为模块对象（import结果）
        return typeof value === 'object' && 'default' in value
      }
    },
    paddingBetween: {
      type: Number,
      default: 40
    }
  },
  computed: {
    resolvedBackground() {
      if (!this.backgroundImage) return ''

      // 处理 import 导入的模块对象
      if (typeof this.backgroundImage === 'object') {
        return `url(${this.backgroundImage.default})`
      }

      // 处理网络路径和base64
      return `url(${this.backgroundImage})`
    }
  },
  setup(props) {
    const state = reactive({
      transform: ''
    })

    return {
      ...toRefs(state)
    }
  }
})
</script>

<template>
  <div class="component-login-template-container"
       :style="{padding: `0 ${paddingBetween}px`, backgroundColor, backgroundImage: resolvedBackground}">
    <div class="form-bound" :style="{transform}" :class="formPosition">
      <slot />
    </div>
  </div>
</template>

<style lang="scss">
.component-login-template-container {
  height: 100%;
  position: relative;

  .form-bound {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
    align-items: center;
    justify-content: center;

    &.left {
      left: 0;
    }

    &.right {
      right: 0;
    }

    &.center {
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
}
</style>
